package com.freely.util;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;

public class VerificationUtil {
	private Random random = new Random();
	private int width = 100;	
	private int height = 50;
	private String[] fonts = {"宋体","华文楷体","黑体","微软雅黑"};
	private String value = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ";
	private Color bgColor = new Color(255,255,255);
	private String text;
	
	private Color randomColor() {
		int r = random.nextInt(150);
		int g = random.nextInt(150);
		int b = random.nextInt(150);
		return new Color(r,g,b);
	}
	
	private Font randomFont() {
		int index = random.nextInt(fonts.length);
		String font = fonts[index];
		int style = random.nextInt(4);
		int size = random.nextInt(5) + 25;
		return new Font(font,style,size);
	}
	
	private void drawLine(BufferedImage image) {
		Graphics2D graphic = (Graphics2D) image.getGraphics();
		for(int i = 0;i < 3;i++) {
			int x1 = random.nextInt(width);
			int x2 = random.nextInt(width);
			int y1 = random.nextInt(height);
			int y2 = random.nextInt(height);
			graphic.setStroke(new BasicStroke(1.5F));
			graphic.setColor(Color.blue);
			graphic.drawLine(x1, y1, x2, y2);
		}
	}
	
	private char randomChar() {
		int index = random.nextInt(value.length());
		return value.charAt(index);
	}
	
	private BufferedImage createImage() {
		BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics = (Graphics2D) image.getGraphics();
		graphics.setColor(this.bgColor);
		graphics.fillRect(0, 0, width, height);
		return image;
	}
	
	private BufferedImage getImage() {
		BufferedImage image = createImage();
		Graphics2D graphics = (Graphics2D) image.getGraphics();
		StringBuilder sb = new StringBuilder();
		for(int i = 0;i < 4;i++) {
			String str = randomChar() + "";
			sb.append(str);
			float x = i * 1.0F * width / 4;
			graphics.setFont(randomFont());
			graphics.setColor(randomColor());
			graphics.drawString(str, x, height - 8);
		}
		drawLine(image);
		this.text = sb.toString();
		return image;
	}
	
	public String getText() {
		return text;
	}
	
	public byte[] getImageByte() {
		BufferedImage bufImage = getImage();
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		try {
			ImageIO.write(bufImage, "jpg", output);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return output.toByteArray();
	}
	
	
	
}
